import 'package:dio/dio.dart';
import 'package:flutter_demo/entities/article_item.dart';
import 'package:flutter_demo/utils/dom_parser.dart';
import 'package:flutter_demo/views/loading_container.dart';
import 'package:get/get.dart';

class ArticleListController extends GetxController {
  var list = List<ArticleItem>.empty(growable: true).obs;
  var listLoadingStatus = LoadStatus.loading.obs;
  var page = 1;
  var hasMore = true.obs;

  @override
  onReady() {
    super.onReady();
    getList();
  }

  getList({bool init = true}) async {
    if (list.isNotEmpty) {
      listLoadingStatus.value = LoadStatus.success;
    }
    var requestPage = page;
    if (!init) {
      requestPage++;
    }
    try {
      final response = await Dio().get<String>("https://fourpetal.com/page/$requestPage");
      final result = DomParser.parseArtilceList(response.data);
      hasMore.value = result.length >= 15;
      page = requestPage;
      if (init) {
        list.clear();
      }
      list.addAll(result);
    } catch(_) {
    }

    if (list.isEmpty) {
      listLoadingStatus.value = LoadStatus.empty;
    } else {
      listLoadingStatus.value = LoadStatus.success;
    }
  }
}
